<template>
  <div class="divBox">
    <el-card class="box-card" shadow="never" :bordered="false">
      <div class="padding-add">
        <el-form ref="form" inline :model="tableFrom">
          <el-form-item label="文件名：">
            <el-input v-model.trim="tableFrom.fileName" placeholder="请输入文件名" size="small"></el-input>
          </el-form-item>
          <el-form-item label="赛事ID：">
            <el-input-number
              v-model="tableFrom.competitionId"
              :min="1"
              placeholder="请输入赛事ID"
              size="small"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="文章语言：">
            <el-select v-model="tableFrom.isEng" clearable class="selWidth" placeholder="请选择文章语言">
              <el-option :value="0" label="中文"></el-option>
              <el-option :value="1" label="英文"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getList(1)">查询</el-button>
            <el-button size="small" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card mt14" shadow="never" :bordered="false">
      <el-button type="primary" class="mb20" size="small" @click="handlerAdd">新增文件</el-button>

      <el-table v-loading="loading" :data="tableData.data" size="small">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="赛事ID" prop="competitionId" width="100" />
        <el-table-column label="文件语言" width="100">
          <template slot-scope="scope">
            {{ scope.row.isEng === 0 ? '中文' : '英文' }}
          </template>
        </el-table-column>
        <el-table-column label="文件名" prop="fileName" min-width="150" />
        <el-table-column label="文件链接" prop="fileUrl" min-width="200">
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.fileUrl"
              type="primary"
              :href="formatFileUrl(scope.row.fileUrl)"
              target="_blank"
              @click="downloadFile(scope.row.fileUrl, scope.row.fileName)"
            >
              {{ formatFileUrl(scope.row.fileUrl) }}
            </el-link>
            <span v-else class="text-muted">暂无文件</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort" width="80" />
        <el-table-column label="创建时间" prop="createTime" width="150" />
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <a @click="handleDetail(scope.row)">查看详情</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="handleDelete(scope.row.id)">删除</a>
          </template>
        </el-table-column>
      </el-table>

      <div class="block-pagination">
        <el-pagination
          background
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @current-change="pageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增弹窗 -->
    <el-dialog title="新增文件" :visible.sync="dialogVisible" width="600px">
      <el-form :model="formData" :rules="rules" ref="formData" label-width="100px">
        <el-form-item label="赛事ID：" prop="competitionId">
          <el-input-number v-model="formData.competitionId" :min="1" placeholder="请输入赛事ID"></el-input-number>
        </el-form-item>
        <el-form-item label="文件名：" prop="fileName">
          <el-input v-model.trim="formData.fileName" placeholder="请输入文件名"></el-input>
        </el-form-item>
        <el-form-item label="文章语言：">
          <el-select v-model="formData.isEng" clearable class="selWidth" placeholder="请选择文章语言">
            <el-option :value="0" label="中文"></el-option>
            <el-option :value="1" label="英文"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件：" prop="fileUrl">
          <upload-file v-model="formData.fileUrl" />
          <div class="upload-tip">支持上传各种格式文件，上传后会自动获取文件链接</div>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input-number v-model="formData.sort" :min="1" placeholder="请输入排序"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm('formData')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  competitionFileSaveApi,
  competitionFileListApi,
  competitionFileDetailApi,
  competitionFileDeleteApi,
} from '@/api/competitionFile';
import { handleDeleteTable } from '@/libs/public';
import { Debounce } from '@/utils/validate';
import UploadFile from '@/components/Upload/uploadFile.vue';

export default {
  name: 'CompetitionFile',
  components: {
    UploadFile,
  },
  data() {
    return {
      tableFrom: {
        page: 1,
        limit: 20,
        fileName: '',
        competitionId: '',
      },
      loading: false,
      dialogVisible: false,
      tableData: {
        data: [],
        total: 0,
      },
      formData: {
        competitionId: '',
        fileName: '',
        isEng: 0,
        fileUrl: '',
        sort: 1,
      },
      rules: {
        competitionId: [{ required: true, message: '请填写赛事ID', trigger: 'blur' }],
        fileName: [{ required: true, message: '请填写文件名', trigger: 'blur' }],
        isEng: [{ required: true, message: '请选择文章语言', trigger: 'change' }],
        fileUrl: [{ required: true, message: '请上传文件', trigger: 'blur' }],
        sort: [{ required: true, message: '请填写排序', trigger: 'blur' }],
      },
    };
  },
  mounted() {
    this.getList(1);
  },
  methods: {
    handlerAdd() {
      this.dialogVisible = true;
      this.formData = {
        competitionId: '',
        fileName: '',
        isEng: 0,
        fileUrl: '',
        sort: 1,
      };
    },
    resetForm() {
      this.tableFrom.fileName = '';
      this.tableFrom.isEng = null;
      this.tableFrom.competitionId = '';
      this.getList(1);
    },
    handleDetail(row) {
      this.$message.info('查看详情功能待实现');
    },
    handleDelete(id) {
      this.$modalSure('删除该文件吗？').then(() => {
        competitionFileDeleteApi(id).then(() => {
          this.$message.success('删除成功');
          handleDeleteTable(this.tableData.data.length, this.tableFrom);
          this.getList();
        });
      });
    },
    getList(num) {
      this.loading = true;
      this.tableFrom.page = num ? num : this.tableFrom.page;
      competitionFileListApi(this.tableFrom)
        .then((res) => {
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList();
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList();
    },
    submitForm: Debounce(function (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          competitionFileSaveApi(this.formData).then((res) => {
            this.$message.success('新增成功');
            this.getList(1);
            this.dialogVisible = false;
          });
        }
      });
    }),
    formatFileUrl(url) {
      // 处理文件链接，确保以 http:// 或 https:// 开头
      if (!url) return '';

      // 如果URL包含重复的域名，只保留一个
      if (url.includes('https://toyadmin.reh.cn/https://toyadmin.reh.cn/')) {
        url = url.replace('https://toyadmin.reh.cn/https://toyadmin.reh.cn/', 'https://toyadmin.reh.cn/');
      }

      // 确保URL以 http:// 或 https:// 开头
      if (!url.startsWith('http://') && !url.startsWith('https://')) {
        return 'https://' + url;
      }

      return url;
    },
    downloadFile(url, fileName) {
      if (!url) {
        this.$message.warning('文件链接不存在，无法下载');
        return;
      }

      const formattedUrl = this.formatFileUrl(url);

      try {
        const link = document.createElement('a');
        link.href = formattedUrl;
        link.download = fileName || 'download'; // 如果没有文件名，则使用默认的下载名
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success('开始下载文件');
      } catch (error) {
        console.error('下载文件失败:', error);
        this.$message.error('下载文件失败，请检查文件链接是否正确');
      }
    },
  },
};
</script>

<style scoped lang="scss">
.detail-content {
  .el-descriptions-item__label {
    width: 120px;
  }
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.text-muted {
  color: #999;
  font-size: 12px;
}

// 下载链接样式
.el-link {
  .el-icon-download {
    margin-right: 4px;
  }
}
</style>
